package com.habdqn.easybuy.service.impl;

import com.habdqn.easybuy.dao.ProductCategoryDao;
import com.habdqn.easybuy.dao.impl.ProductCategoryDaoImpl;
import com.habdqn.easybuy.entity.ProductCategory;
import com.habdqn.easybuy.service.ProductCategoryService;

import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/11/30
 */
public class ProductCategoryServiceImpl implements ProductCategoryService {
    private ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl();

    @Override
    public ProductCategory queryById(Integer id) {
        return productCategoryDao.queryById(id);
    }

    @Override
    public List<ProductCategory> queryAll() {
        // 先查询顶级分类
        List<ProductCategory> categories = queryByParentId(0);
        // 遍历顶级分类
        categories.forEach(category -> {
            // 查询对应的二级分类并组装
            category.setSubCategories(queryByParentId(category.getId()));
        });
        return categories;
    }

    /**
     * 根据父分类ID查询分类集合
     *
     * @param parentId 父分类id
     * @return 子分类集合
     */
    @Override
    public List<ProductCategory> queryByParentId(int parentId) {
        return productCategoryDao.queryByParentId(parentId);
    }

    @Override
    public ProductCategory insert(ProductCategory productCategory) {
        productCategory.setId(productCategoryDao.insert(productCategory));
        return productCategory;
    }

    @Override
    public ProductCategory update(ProductCategory productCategory) {
        if (productCategoryDao.update(productCategory)>0){
            return productCategory;
        }
        return null;
    }

    @Override
    public boolean deleteById(Integer id) {
        return productCategoryDao.deleteById(id)>0;
    }
}
